package com.thinkgem.jeesite.common.utils;

import com.alibaba.druid.support.logging.Log;
import com.alibaba.druid.support.logging.LogFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;

public class HttpClientUtil{

    private final static Log LOG = LogFactory.getLog(HttpClientUtil.class);
    public static String post(String serverUrl, String data, int timeout) {
        String responseBuilder = "";
        BufferedReader reader = null;
        OutputStreamWriter wr = null;

        URL url;
        try {
            url = new URL(serverUrl);
            URLConnection conn = url.openConnection();
            conn.setDoOutput(true);
            conn.setConnectTimeout(timeout);
            wr = new OutputStreamWriter(conn.getOutputStream());

            wr.write(data);
            wr.flush();

            reader = new BufferedReader(new InputStreamReader(conn.getInputStream(),"utf8"));
            String line;
            while ((line = reader.readLine()) != null) {
                responseBuilder += line;
            }
            return responseBuilder;
        } catch (IOException e) {
            LOG.error("", e);
        } finally {

            if (wr != null) {
                try {
                    wr.close();
                } catch (IOException e) {
                    LOG.error("close error", e);
                }
            }

            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    LOG.error("close error", e);
                }
            }

        }
        return "";
    }

}
